package cn.iocoder.yudao.module.bpm.framework.flowable.core.listener.demo.task;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
import cn.iocoder.yudao.framework.magic.api.MagicApiExcuse;
import cn.iocoder.yudao.framework.magic.api.dto.ExcuseMagicApiDTO;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 类型为 magicApiDelegateExpressionTaskListener 的 TaskListener 监听器示例
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class MagicApiDelegateExpressionTaskListener implements TaskListener {


    private Expression method ;
    private Expression path ;

    @Autowired
    MagicApiExcuse magicApiExcuse ;
    @Autowired
    BpmProcessInstanceService bpmProcessInstanceService ;

    @Override
    public void notify(DelegateTask delegateTask) {
        log.info("[execute][task({}) 被调用]", delegateTask.getId());

        Map<String, Object> context = new HashMap<>();

        ProcessInstance processInstance = bpmProcessInstanceService.getProcessInstance(delegateTask.getProcessInstanceId());

        context.put("businessKey", processInstance.getBusinessKey());
        context.put("processInstanceId", delegateTask.getProcessInstanceId());
        context.put("taskDefinitionKey", delegateTask.getTaskDefinitionKey());
        context.put("eventName", delegateTask.getEventName());

        context.putAll(delegateTask.getVariables());

        ExcuseMagicApiDTO excuseMagicApiDTO = new ExcuseMagicApiDTO();
        excuseMagicApiDTO.setMethod(method.getExpressionText());
        excuseMagicApiDTO.setPath(path.getExpressionText());
        excuseMagicApiDTO.setContext(context);

        magicApiExcuse.excuseMagicApi(excuseMagicApiDTO);
    }

}
